<?php
/**
 * Created by PhpStorm.
 * User: zhou
 * Date: 2019/4/15
 * Time: 上午10:18
 */

namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class HotelGoods extends Model
{

    protected $table = 'hotel_goods';
    protected $fillable = ['hotel_id','goods_id','stock','updated_at','created_at','is_on_sale'];

    public static $error;

    public static $model;

    /**
     * 酒店商品列表
     * @param $postData ['goods.goods_id'=>1]
     */
    public static function hotel_goods_list($postData)
    {
        $self_table = (new static()) -> table;
        $query = self::query()
            -> join('goods','goods.goods_id','=',$self_table.'.goods_id')
            -> join('hotel','hotel.hotel_id','=',$self_table.'.hotel_id')
//            -> where('is_on_sale','=',1)
            -> select(
                $self_table.'.is_on_sale',
                'hotel.name AS hotel_name','hotel.hotel_id',
                'goods.goods_id','goods.goods_name',
                'goods.image','goods.stock AS total_stock',
                $self_table.'.stock AS hotel_stock',
                DB::raw('IFNULL(discount_price,price) discount_price'),
                'goods.price'
            );
        foreach($postData as $field => $value){
            if($field == 'goods_id'){
                $query -> where('goods.'.$field,'=',$value);
            }else{
                $query -> where($field,'=',$value);
            }

        }
        return $query -> get() -> toArray();
    }

    /**商品管理--批量更新该商品的酒店库存
     * @param $postData
     * [
     *   ['goods_id'=>1,'update_stock'=> 12,hotel_id=>1],
     *   ['goods_id'=>1,'update_stock'=> -5,hotel_id=>2],
     * ]
     */
    public static function update_stock($postData)
    {
        try{
            DB::beginTransaction();
            $total_stock = 0;
            $goods_id = 0;

            #更新该商品的酒店库存
            foreach($postData as $key => $update_data){
                $goods_id = $update_data['goods_id'];
                #传递过来的需要更新的库存为0则不做任何操作
                if($update_data['update_stock'] == 0){
                    continue;
                }

                $update_type = $update_data['update_stock'] < 0 ? 'decrement' : 'increment';
                $total_stock += $update_data['update_stock'];

                $update_stock = abs($update_data['update_stock']);
                $query = self::query()
                    -> where('goods_id','=', $update_data['goods_id'])
                    -> where('hotel_id','=',$update_data['hotel_id']);

                if($update_type === 'decrement'){
                    $res = $query -> decrement('stock',$update_stock);
                }else{
                    $res = $query -> increment('stock',$update_stock);
                }
                if(!$res){
                    throw new \Exception('更新酒店id为'.$update_data['hotel_id'].'的库存失败');
                }
            }

            #更新该商品的总库存
            if($total_stock < 0){
                $res = Goods::query()
                    ->where('goods_id','=',$goods_id)
                    ->increment('stock',abs($total_stock));
                if(!$res){
                    throw new \Exception('更新该商品总库存失败!');
                }
            }else if($total_stock > 0){
                $res = Goods::query()
                    ->where('goods_id','=',$goods_id)
                    ->decrement('stock',abs($total_stock));
                if(!$res){
                    throw new \Exception('更新该商品总库存失败!');
                }
            }

            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            self::$error = $exception -> getMessage();
            return false;
        }
    }

    /**
     * 该方法仅仅用于设置该酒店某个商品的库存值
     * 调整只适用于货物丢失损坏等不可恢复的异常情况
     */
    public static function update_hotel_goods_stock($postData)
    {
        $model =  self::query()
            -> where('hotel_id','=',$postData['hotel_id'])
            -> where('goods_id','=',$postData['goods_id'])
            -> first();
        if(empty($model)){
            return true;
        }

        if($model -> stock == $postData['stock']){
            return true;
        }

        $model -> stock = $postData['stock'];
        return $model -> save();
    }

    /**
     * 删除该酒店下的停售的商品
     * 确保该商品库存为0 才能删除
     * 确保该商品是未出售的商品
     */
    public static function delete_hotel_goods($postData)
    {
        $hotelGoodsModel = self::query()
            -> where('hotel_id','=',$postData['hotel_id'])
            -> where('goods_id','=',$postData['goods_id'])
            -> first();
        if(empty($hotelGoodsModel)){
            return true;
        }
        if($hotelGoodsModel -> is_on_sale == 1){
            self::$error = '该商品是是在售商品，无法删除!';
            return false;
        }
        if($hotelGoodsModel -> stock > 0 ){
            self::$error = '该商品还有库存，无法删除!请核对库存后，确保库存为0后再进行操作!';
            return false;
        }

        $hotelGoodsModel -> delete();
        return true;
    }

    /**
     *用于后台酒店--商品列表中的商品列表
     */
    public static function on_sale_goods($hotel_id)
    {
        return self::hotel_goods_list([
            'hotel.hotel_id' => $hotel_id,
            'is_on_sale'     => 1,
        ]);
    }

    /**
     * 用于后台酒店--商品列表中的商品列表
     */
    public static function off_sale_goods($hotel_id)
    {
        return self::hotel_goods_list([
            'hotel.hotel_id' => $hotel_id,
            'is_on_sale'     => 0,
        ]);
    }


    public static function getHotelGoodsInfo($hotel_id,$goods_id)
    {
        $self = (new static);
        $query = self::query()
            -> where($self->table.'.goods_id','=',$goods_id)
            -> where('hotel_id','=',$hotel_id);

        self::$model = $query -> first();
        $model = $query
            -> select(
                'goods.goods_name','goods.goods_id','goods.stock AS total_stock','goods.marketable',
                'goods.disabled',$self->table.'.is_on_sale',$self->table.'.stock AS hotel_stock'
            )
            -> leftJoin('goods','goods.goods_id','=',$self->table.'.goods_id')
            -> first();
        return empty($model) ? false : $model -> toArray();
    }
}